package com.dobbinsoft.iotechn.apigw.ws.handler;

import com.alibaba.fastjson.JSONObject;
import com.dobbinsoft.iotechn.apigw.enums.WebsocketMessageType;
import com.dobbinsoft.iotechn.apigw.ws.DataPointWebsocket;
import com.dobbinsoft.iotechn.apigw.ws.message.DeviceDataSnapshotMessage;
import com.dobbinsoft.iotechn.apigw.ws.message.DeviceSelectWsMessage;
import com.dobbinsoft.iotechn.device.api.biz.DeviceBizService;
import com.dobbinsoft.iotechn.device.entity.DeviceDataSnapshotEntity;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Description:
 * User: rize
 * Date: 2020/6/28
 * Time: 15:18
 */
public class DeviceSelectWsHandler implements WebsocketHandler<DeviceSelectWsMessage> {

    @Autowired
    private DeviceBizService deviceBizService;

    @Override
    public int handle(Object websocket, DeviceSelectWsMessage deviceSelectWsMessage) {
        DataPointWebsocket dataPointWebsocket = (DataPointWebsocket) websocket;
        Long deviceId = deviceSelectWsMessage.getDeviceId();
        dataPointWebsocket.setCurrentDevice(deviceId);
        // 通过Socket返回Hash快照
        List<DeviceDataSnapshotEntity> deviceDataSnapshotEntities = deviceBizService.listDeviceData(deviceId);
        DeviceDataSnapshotMessage deviceDataSnapshotMessage = new DeviceDataSnapshotMessage();
        deviceDataSnapshotMessage.setCode(WebsocketMessageType.DATA_SNAPSHOOT.getCode());
        Map<String, DeviceDataSnapshotEntity> map = deviceDataSnapshotEntities.stream().collect(Collectors.toMap(DeviceDataSnapshotEntity::getIdTag, item -> item));
        deviceDataSnapshotMessage.setSnapshots(map);
        dataPointWebsocket.sendMessage(JSONObject.toJSONString(deviceDataSnapshotMessage));
        return 1;
    }

    @Override
    public int getCode() {
        return WebsocketMessageType.DEVICE_SELECT.getCode();
    }

    @Override
    public Class<DeviceSelectWsMessage> getMessageType() {
        return DeviceSelectWsMessage.class;
    }
}
